package fr.lostnet.mapview;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;

import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.util.Log;

public class RemoteService extends AsyncTask<String, Void, String> {

	private static final String LOG_TAG = "RemoteService";
	private static final String HTTP_USER_AGENT = "MapView/1.0 Development";

	private RemoteListener listener_;
	private AndroidHttpClient client_ = AndroidHttpClient.newInstance(HTTP_USER_AGENT);

	public RemoteService(RemoteListener listener) {
		listener_ = listener;
	}

	@Override
	protected String doInBackground(String... param) {
		return callWebService(param[0]);
	}

	protected void onPostExecute(final String result) {
		listener_.onRequestComplete(result);
	}

	private String callWebService(String url) {

		HttpGet request = new HttpGet(url);
		try {
			HttpResponse response = client_.execute(request);
			int status = response.getStatusLine().getStatusCode();
			if (status != HttpStatus.SC_OK) {
				Log.w(LOG_TAG, "Error " + status
						+ " while accessing web service " + url);
				return null;
			}
			InputStream content = response.getEntity().getContent();
			return convertStreamToString(content);
		} catch (IOException e) {
			Log.e(LOG_TAG, "Error while executing http request for " + url);
			request.abort();
			return null;
		} finally {
			client_.close();
		}
	}

	private static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		try {
			try {
				for (String line = null; (line = reader.readLine()) != null;) {
					sb.append(line + "\n");
				}
				return sb.toString();
			} finally {
				is.close();
			}
		} catch (IOException e) {
			Log.e(LOG_TAG, "Error while converting input stream", e);
			return null;
		}
	}

}
